package com.dy.mongo.controller;

import com.dy.mongo.dto.PersonDetailDto;
import com.dy.mongo.dto.RelationPerson;
import com.dy.mongo.entity.Person;
import com.dy.mongo.repository.*;
import com.dy.mongo.service.CsvImportService;
import com.opencsv.exceptions.CsvValidationException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * 提供导入与查询接口。
 */
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class GraphController {

    private final CsvImportService importService;
    private final PersonRepository personRepo;
    private final PersonImageRepository imageRepo;
    private final PersonVideoRepository videoRepo;
    private final PersonTextRepository textRepo;

    /**
     * 触发 CSV 导入。
     * GET /api/import?char=path1&rel=path2
     */
    @PostMapping("/import")
    public ResponseEntity<?> importCsv(@RequestParam(defaultValue = "characters.csv") String charPath,
                                       @RequestParam(defaultValue = "relations.csv") String relPath) throws IOException, CsvValidationException {
        Path characters = Paths.get(charPath);
        Path relations = Paths.get(relPath);
        if (!Files.exists(characters) || !Files.exists(relations)) {
            return ResponseEntity.badRequest().body("CSV 文件不存在");
        }
        importService.importCharactersAndRelations(characters, relations);
        return ResponseEntity.ok("导入成功");
    }

    /**
     * 直接上传 CSV 文件导入（multipart/form-data）。
     * POST /api/import/upload
     * form-data 字段： characters=<file>, relations=<file>
     */
    @PostMapping(value = "/import/upload", consumes = "multipart/form-data")
    public ResponseEntity<?> importCsvUpload(@RequestPart("characters") MultipartFile characters,
                                             @RequestPart("relations") MultipartFile relations) throws IOException, CsvValidationException {
        if (characters.isEmpty() || relations.isEmpty()) {
            return ResponseEntity.badRequest().body("上传文件不能为空");
        }
        importService.importCharactersAndRelations(characters, relations);
        return ResponseEntity.ok("上传导入成功");
    }

    /**
     * 查询人物详情，包括关系与媒体资源。
     * GET /api/person/{csvId}
     */
    @GetMapping("/person/{csvId}")
    public ResponseEntity<?> getPerson(@PathVariable Long csvId) {
        Person p = personRepo.findByCsvId(csvId);
        if (p == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(toDto(p));
    }

    /**
     * 根据名字查询人物（完全匹配）。
     * GET /api/person/name/{name}
     */
    @GetMapping("/person/name/{name}")
    public ResponseEntity<?> getPersonByName(@PathVariable String name) {
        Person p = personRepo.findByName(name);
        if (p == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(toDto(p));
    }

    /** 将 Person 转为 DTO */
    private PersonDetailDto toDto(Person p) {
        Map<String, List<RelationPerson>> relMap = new HashMap<>();
        //把人物关系提取到relMap
        p.getRelations().forEach((type, list) -> {
            List<RelationPerson> persons = list.stream()
                    .filter(per -> per.getCsvId() != null)
                    .map(per -> new RelationPerson(per.getCsvId(), per.getName()))
                    .toList();
            relMap.put(type, persons);
        });

        return new PersonDetailDto(
                p.getCsvId(),
                p.getName(),
                p.getAlias(),
                p.getSpecies(),
                relMap,
                imageRepo.findByCsvId(p.getCsvId()),
                videoRepo.findByCsvId(p.getCsvId()),
                textRepo.findByCsvId(p.getCsvId())
        );
    }
} 